package File;

import java.io.*;
import java.util.Scanner;

public class demo16 {
    public static void main(String[] args) {
        System.out.println("请输入你要搜索的目录");
        Scanner scanner=new Scanner(System.in);
        String searchpath=scanner.next();
        File searchdirectory=new File(searchpath);
        if(!searchdirectory.isDirectory()){
            System.out.println("你输入的不是目录");
            return;
        }
        System.out.println("请输入你要查找的关键字");
        Scanner scanner1=new Scanner(System.in);
        String keyword=scanner1.next();
        Search(searchdirectory,keyword);
    }

    private static void Search(File searchdirectory, String keyword) {
        File[] files=searchdirectory.listFiles();
        if(files==null){
            return;
        }
        for(File file:files){
            if(file.isDirectory()){
                Search(file,keyword);
            }
            if(file.isFile()){
                Lookup(file,keyword);
            }
        }
    }

    private static void Lookup(File file, String keyword) {
        if(file.getName().contains(keyword)){
            System.out.println("找到了含有关键字的指定文件了"+file.getAbsolutePath());
        }
        //使用StringBuffer来记录内容
        StringBuffer stringBuffer=new StringBuffer();
        //因为keyword是字符串，就使用Reader了
        try(Reader reader=new FileReader(file)){
           while(true){
               char[] chars=new char[1024];
               int n=reader.read(chars);
               if(n==-1){
                   break;
               }
               stringBuffer.append(chars,0,n);
           }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //找得到keyword，就返回下标，找不到就返回-1
        if(stringBuffer.indexOf(keyword)>=0){
            System.out.println("内容包含关键字"+file.getAbsolutePath());

        }
    }

}
